<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()
const router = useRouter()
const username = ref('')
const password = ref('')
const loading = ref(false)

const login = async () => {
  if (!username.value || !password.value) {
    alert('请输入用户名和密码')
    return
  }

  loading.value = true
  try {
    console.log('开始登录，凭据:', {
      username: username.value,
      password: password.value,
    })

    const result = await userStore.login({
      username: username.value,
      password: password.value,
    })

    console.log('登录结果:', result)

    if (result.success) {
      console.log('登录成功，token:', userStore.token)
      // 获取用户信息
      await userStore.fetchUserInfo()
      router.push('/index')
    } else {
      alert(result.message || '登录失败')
    }
  } catch (error) {
    console.error('登录错误:', error)
    alert('登录过程中发生错误: ' + error.message)
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <div class="login-container">
    <div class="login-form">
      <h2>用户登录</h2>
      <div class="form-group">
        <label for="username">用户名:</label>
        <input
          id="username"
          v-model="username"
          type="text"
          placeholder="请输入用户名"
          class="form-input"
        />
      </div>
      <div class="form-group">
        <label for="password">密码:</label>
        <input
          id="password"
          v-model="password"
          type="password"
          placeholder="请输入密码"
          class="form-input"
        />
      </div>
      <button @click="login" :disabled="loading" class="login-button">
        {{ loading ? '登录中...' : '登录' }}
      </button>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}

.login-form {
  background-color: white;
  padding: 2rem;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  width: 350px;
}

h2 {
  text-align: center;
  margin-bottom: 1.5rem;
  color: #333;
}

.form-group {
  margin-bottom: 1rem;
}

label {
  display: block;
  margin-bottom: 0.5rem;
  color: #333;
}

.form-input {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
  box-sizing: border-box;
}

.form-input:focus {
  outline: none;
  border-color: #409eff;
}

.login-button {
  width: 100%;
  padding: 0.75rem;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 1rem;
  cursor: pointer;
  margin-top: 1rem;
}

.login-button:hover:not(:disabled) {
  background-color: #337ecc;
}

.login-button:disabled {
  background-color: #a0cfff;
  cursor: not-allowed;
}
</style>
